import java.util.HashMap;
import java.util.Map;

public class Solution1171 {

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode removeZeroSumSublists(ListNode head) {
        ListNode listNode=new ListNode(-1,head);
        Map<Integer,ListNode> re=new HashMap<>();
        re.put(0,listNode);
        int count=0;
        while (head!=null){
            count+=head.val;
            if (!re.containsKey(count)){
                re.put(count,head);
            }else {
                ListNode t=re.get(count);
                ListNode tt=t.next;
                int p=count;
                while (tt!=head){
                    p+=tt.val;
                    re.remove(p);
                    tt=tt.next;
                }
                t.next=head.next;
            }
            head=head.next;
        }
        return listNode.next;
    }

    public static void main(String[] args) {
        System.out.println(new Solution1171().removeZeroSumSublists(new ListNode(1,new ListNode(3,new ListNode(2,new ListNode(-3,new ListNode(-2,new ListNode(5,new ListNode(5,new ListNode(-5,new ListNode(1)))))))))).next.next.val);
    }
}
